<template>
  <div class="page">
    <div class="head">
      <h1>{{ $t('道具城') }}</h1>
    </div>
    <!-- <div class="goods">
      <div :class="{'active': item.value == goods}" v-for="(item,index) in goodsItems" @click="changeGoods(item.value)" :key="'goods-'+index">{{ item.name }}</div>
    </div> -->
    <div class="item-filter">
      <ul class="status">
        <li :class="{'active': item.value == goods}" v-for="(item,index) in goodsItems" @click="changeGoods(item.value)" :key="'goods-'+index">{{ item.name }}</li>
      </ul>
    </div>
    <div class="panel">
      <x-table :cell-bordered="false" :content-bordered="false" class="item-table">
        <thead>
          <tr style="background-color: #F7F7F7">
            <th>卖/买家</th>
            <th>数量</th>
            <th>单价</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item,index) in sellList" :key="'sell-'+index">
            <td class="name">{{ item.userName }}</td>
            <td>{{ item.balanceNum }}</td>
            <td>{{ item.price }} 毛</td>
            <td>
              <x-button mini plain type="primary" @click.native="confirmNum(item)">购买</x-button>
            </td>
          </tr>
          <tr class="dash" v-if="sellList.length > 0 && buyList.length > 0">
            <td></td>
            <td></td>
            <td></td>
            <td></td>
          </tr>
          <tr v-for="(item,index) in buyList" :key="'buy-'+index">
            <td class="name">{{ item.userName }}</td>
            <td>{{ item.balanceNum }}</td>
            <td>{{ item.price }} 毛</td>
            <td>
              <x-button class="sell-button" mini plain @click.native="confirmNum(item)">出售</x-button>
            </td>
          </tr>
        </tbody>
      </x-table>
      <empty v-if="sellList.length == 0 && buyList.length == 0"></empty>
    </div>
    <div class="panel">
      <div class="filter">
        <ul class="status">
          <li v-for="(item, index) in category" :class="{'active': index == activeIndex}" @click="changeCategory(index)" :key="index">{{item}}</li>
        </ul>
      </div>
      <swiper :options="swiperOption" ref="mySwiper" class="item-swiper">
        <swiper-slide class="buy order">
          <p>可用猴毛： <span>{{ balance.coinBalance }}</span></p>
          <group gutter="5px">
            <x-input :title="`购买${goodsArr[goods]}单价：`" placeholder="输入单价" type="number" :min="0" v-model="buy.price"></x-input>
            <x-input :title="`购买${goodsArr[goods]}数量：`" placeholder="输入数量" type="number" :min="0" v-model="buy.num"></x-input>
          </group>
          <x-button class="button" :plain="goods != 0" type="primary" :disabled="goods == 0" @click.native="confirmPublishOrder(buy)">挂{{goodsArr[goods]}}买单</x-button>
        </swiper-slide>
        <swiper-slide class="sell order">
          <p v-if="goods == 1">可用{{ goodsArr[goods] }}： <span>{{ balance.peenToBalance || 0 }}</span></p>
          <p v-if="goods == 2">可用{{ goodsArr[goods] }}： <span>{{ balance.stoneBalance  || 0 }}</span></p>
          <p v-if="goods == 3">可用{{ goodsArr[goods] }}： <span>{{ balance.cloudBalance  || 0 }}</span></p>
          <p v-if="goods == 4">可用{{ goodsArr[goods] }}： <span>{{ balance.ticketBalance  || 0 }}</span></p>
          <p v-if="goods == 5">可用{{ goodsArr[goods] }}： <span>{{ balance.xrpBalance  || 0 }}</span></p>
          <p v-if="goods == 6">可用{{ goodsArr[goods] }}： <span>{{ balance.resurgenceBookBalance  || 0 }}</span></p>
          <p v-if="goods == 7">可用{{ goodsArr[goods] }}： <span>{{ balance.resurgenceStoneBalance  || 0 }}</span></p>
          <p v-if="goods == 9">可用{{ goodsArr[goods] }}： <span>{{ balance.wkbNum  || 0 }}</span></p>
          <group gutter="5px">
            <x-input :title="`出售${goodsArr[goods]}单价：`" placeholder="输入单价" type="number" v-model="sell.price"></x-input>
            <x-input :title="`出售${goodsArr[goods]}数量：`" placeholder="输入数量" type="number" v-model="sell.num"></x-input>
          </group>
          <x-button class="button" type="warn" :disabled="goods == 0" @click.native="confirmPublishOrder(sell)">挂{{goodsArr[goods]}}卖单</x-button>
        </swiper-slide>
        <swiper-slide class="sell order">
          <x-table :cell-bordered="false" :content-bordered="false" class="item-table">
            <thead>
              <tr style="background-color: #F7F7F7">
                <th>类型</th>
                <th>时间</th>
                <th>单价/数量</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item,index) in myOrderList" :key="index">
                <td class="name">{{ item.type == 1 ? '买入' : '卖出'}}{{ goodsArr[item.goods] }}</td>
                <td>{{ item.createTime | shortTime }}</td>
                <td>{{ item.price + '/' + item.num }}</td>
                <td>
                  <x-button mini plain type="primary" @click.native="cancelOrder(item.id, index)">取消</x-button>
                </td>
              </tr>
            </tbody>
          </x-table>
          <empty v-if="myOrderList.length == 0"></empty>
        </swiper-slide>
        <swiper-slide class="sell order">
          <x-table :cell-bordered="false" :content-bordered="false" class="item-table">
            <thead>
              <tr style="background-color: #F7F7F7">
                <th>类型/时间</th>
                <th>成交价</th>
                <th>成交量</th>
                <th>金额</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item,index) in itemRecord" :key="index">
                <td class="name">{{ item.type == 1 ? '买入' : '卖出' }}{{ goodsArr[goods] }}/{{ item.createTime | shortTime }}</td>
                <td>{{ item.price }}</td>
                <td>{{ item.num }}</td>
                <td>{{ item.amount }} 毛</td>
              </tr>
            </tbody>
          </x-table>
          <infinite-loading @infinite="getItemRecord" ref="infiniteLoading1">
            <span slot="no-more"></span>
            <div slot="no-results">
              <br>
              <empty></empty>
            </div>
            <spinner slot="spinner" type="lines"></spinner>
          </infinite-loading>
        </swiper-slide>
      </swiper>
    </div>
    <div class="vux-confirm">
      <div class="vux-x-dialog">
        <transition name="vux-fade">
          <div class="weui-mask" v-show="showConfirm" style=""></div>
        </transition>
        <transition name="vux-dialog">
          <div class="weui-dialog" style="" v-show="showConfirm">
            <div class="weui-dialog__hd" v-if="confirmation.type == 2"><strong class="weui-dialog__title">确认花费{{ (confirmation.num * confirmation.price) | toFix(2) }}根猴毛购买{{ confirmation.num }}个{{ goodsArr[goods] }}吗？</strong></div>
            <div class="weui-dialog__hd" v-else><strong class="weui-dialog__title">确认出售{{ confirmation.num }}个{{ goodsArr[goods] }}获得{{ (confirmation.num * confirmation.price) | toFix(6) }}根猴毛吗？</strong></div>
            <div class="vux-prompt"><input placeholder="输入数量" type="number" v-model="confirmation.num" class="vux-prompt-msgbox"></div>
            <div class="weui-dialog__ft">
              <a href="javascript:;" class="weui-dialog__btn weui-dialog__btn_default" @click="showConfirm = false">取消</a>
              <a href="javascript:;" class="weui-dialog__btn weui-dialog__btn_primary" @click="confirmOrder(confirmation.id,confirmation.num)">确定</a>
            </div>
          </div>
        </transition>
      </div>
    </div>
  </div>
</template>

<script>
  import {
    XTable,
    XButton,
    XInput,
    Group,
    Spinner
  } from 'vux'
  import empty from './common/empty.vue'
  import InfiniteLoading from 'vue-infinite-loading';
  export default {
    components: {
      XTable,
      XButton,
      XInput,
      Group,
      empty,
      InfiniteLoading,
      Spinner
    },
    data() {
      return {
        category: ['购买', '出售', '委单', '记录'],
        activeIndex: 0,
        value: 5455,
        swiperOption: {
          autoHeight: true,
          spaceBetween: 30,
          allowTouchMove: false,
          on: {
            transitionEnd: () => {
              this.activeIndex = this.swiper.activeIndex
            }
          }
        },
        goods: 1,
        goodsItems: [{
            name: '蟠桃',
            value: 1
          },
          {
            name: '石头',
            value: 2
          },
          {
            name: '神仙草',
            value: 3
          },
          {
            name: '抽奖券',
            value: 4
          },
          {
            name: '复活书',
            value: 6
          },
          {
            name: '复活石',
            value: 7
          }
        ],
        goodsArr: ['', '蟠桃', '石头', '神仙草', '抽奖券','', '复活书', '复活石', ''],
        buyList: [],
        sellList: [],
        buy: {
          num: '',
          price: '',
          type: '购买'
        },
        sell: {
          num: '',
          price: '',
          type: '出售'
        },
        myOrderList: [],
        showConfirm: false,
        confirmation: {
          price: 0,
          balanceNum: 0,
          type: '',
          id: null,
          coinType: ''
        },
        timer: null,
        itemRecord: [],
        balance: {
          coinBalance: 0,
          monkeyBalance: 0,
          peenToBalanc: 0
        },
        current: 1,
        safePwd: '',
        official: 0
      }
    },
    computed: {
      swiper() {
        return this.$refs.mySwiper.swiper
      },
      publishOrderType() {
        if (this.activeIndex < 2) {
          return this.activeIndex + 1
        } else {
          return ''
        }
      }
    },
    watch: {
      activeIndex(index) {
        this.clearInput()
        if (index == 2) {
          this.orderList()
        }
        if (index == 3) {
          this.resetData()
        }
      }
    },
    mounted() {
      this.$nextTick(function() {
        this.initData();
        this.getBalance()
        this.timer = setInterval(() => {
          this.initData();
        }, 3000)
      });
    },
    beforeDestroy() {
      clearInterval(this.timer);
    },
    methods: {
      initData() {
        this.$http
          .post(`/game/ordersTopList`, {
            goods: this.goods
          })
          .then(res => {
            if (res.code == 200) {
              this.$vux.loading.hide()
              this.buyList = res.result.buyList || [];
              this.sellList = res.result.sellList || [];
            } else {}
          })
          .catch(function(error) {});
      },
      confirmPublishOrder(data) {
        if (data.num == '' || data.price == '') {
          this.$vux.toast.text('输入有误！')
          return
        }
        var goods = this.goodsArr[this.goods];
        var that = this;
        this.$vux.confirm.show({
          title: this.$t(`挂单确认`),
          content: `
            <p>确认以${data.price}猴毛的单价<strong style="color: red">${data.type}</strong>${data.num}个${goods}吗？</p>
            <p style="color: red">发布成功后，如果被买家拍下付款，${goods}将不能退回哦！</p>
            `,
          confirmText: this.$t('确认挂单'),
          onConfirm() {
            that.publishOrder(data)
          }
        })
      },
      publishOrder(data) {
        this.$http
          .post(`/game/publishOrders`, {
            type: this.publishOrderType,
            goods: this.goods,
            num: data.num,
            price: data.price,
            pwd: this.safePwd
          })
          .then(res => {
            this.safePwd = '';
            if (res.code == 200) {
              this.$vux.loading.show({
                text: this.$t('成功！请稍后')
              })
              this.getBalance()
              this.clearInput()
            } else if (res.code == 603) {
              // 未设置安全密码
              var that = this
              this.$vux.confirm.show({
                title: this.$t(`提示`),
                content: this.$t(`你还未设置安全密码！`),
                confirmText: this.$t('去设置'),
                onConfirm() {
                  that.$router.push('/mine?pwd=true')
                }
              })
            } else if (res.code == 604) {
              // 未输入安全密码
              if (res.msg == this.$t('安全密码错误')) {
                this.$vux.toast.text(res.msg)
              }
              var that = this;
              this.$vux.confirm.prompt(this.$t('请输入安全密码'), {
                title: this.$t('安全验证'),
                inputAttrs: {
                  type: 'password'
                },
                onConfirm(value) {
                  that.safePwd = value;
                  that.publishOrder(data)
                }
              })
            } else {
              this.$vux.toast.text(res.msg)
            }
          })
          .catch(function(error) {});
      },
      changeCategory(index) {
        this.activeIndex = index
        this.swiper.slideTo(index, 300, true);
      },
      changeGoods(value) {
        clearInterval(this.timer)
        this.clearInput()
        this.goods = value
        this.initData()
        this.resetData()
        this.timer = setInterval(() => {
          this.initData();
        }, 3000)
      },
      clearInput() {
        this.buy.num = this.sell.num = ''
        this.buy.price = this.sell.price = ''
      },
      confirmNum(item) {
        this.confirmation = {
          price: item.price,
          num: item.balanceNum,
          type: item.type,
          id: item.id,
          coinType: item.coinType
        }
        console.log(this.confirmation)
        this.showConfirm = true
      },
      confirmOrder(id, num) {
        this.$http
          .post(`/game/v2/receivingOrders`, {
            id: id,
            num: num,
            pwd: this.safePwd,
            official: this.official
          })
          .then(res => {
            this.safePwd = '';
            if (res.code == 200) {
              this.$vux.loading.show({
                text: this.$t('成功！请稍后')
              })
              this.getBalance()
              this.resetData()
              this.showConfirm = false
            } else if (res.code == 603) {
              // 未设置安全密码
              var that = this
              this.$vux.confirm.show({
                title: this.$t(`提示`),
                content: this.$t(`你还未设置安全密码！`),
                confirmText: this.$t('去设置'),
                onConfirm() {
                  that.$router.push('/mine?pwd=true')
                }
              })
            } else if (res.code == 604) {
              // 未输入安全密码
              if (res.msg == this.$t('安全密码错误')) {
                this.$vux.toast.text(res.msg)
              }
              var that = this;
              this.$vux.confirm.prompt(this.$t('请输入安全密码'), {
                title: this.$t('安全验证'),
                inputAttrs: {
                  type: 'password'
                },
                onConfirm(value) {
                  that.safePwd = value;
                  that.confirmOrder(id, num)
                }
              })
            } else {
              this.$vux.toast.text(res.msg)
            }
          })
          .catch(function(error) {
            this.$vux.toast.text(res.msg)
          });
      },
      securityCheck(data) {
        var that = this;
        this.$vux.confirm.prompt(this.$t('请输入安全密码'), {
          title: this.$t('安全验证'),
          inputAttrs: {
            type: 'password'
          },
          onShow() {
            that.$vux.confirm.setInputValue('')
          },
          onConfirm(value) {
            that.publishOrder(data, value)
          }
        })
      },
      orderList() {
        this.$http
          .get(`/game/myOrdersList`)
          .then(res => {
            if (res.code == 200) {
              this.myOrderList = res.result;
            } else {}
          })
          .catch(function(error) {});
      },
      getBalance() {
        this.$http
          .get(`/game/myBalance`)
          .then(res => {
            if (res.code == 200) {
              // this.myOrderList = res.result;
              this.balance = res.result
            } else {}
          })
          .catch(function(error) {});
      },
      getItemRecord($state) {
        this.$http
          .post(`/game/ordersRecordPage`, {
            current: this.current,
            goods: this.goods
          })
          .then(res => {
            if (res.code == 200) {
              if (res.result.total > 0) {
                this.itemRecord = this.itemRecord.concat(res.result.records);
                $state.loaded();
                if (res.result.current < res.result.pages) {
                  this.current += 1;
                } else {
                  $state.complete();
                }
              } else {
                $state.complete();
              }
            } else {}
          })
          .catch(function(error) {});
      },
      resetData() {
        this.current = 1;
        this.itemRecord = []
        this.$refs.infiniteLoading1.$emit('$InfiniteLoading:reset');
      },
      cancelOrder(id, index) {
        this.$http
          .post(`/game/cancelOrders`, {
            id: id
          })
          .then(res => {
            if (res.code == 200) {
              this.myOrderList.splice(index, 1)
              this.$vux.loading.show({
                text: this.$t('成功！请稍后')
              })
            } else {}
          })
          .catch(function(error) {});
      },
    }
  }
</script>

<style lang="scss" scoped>
  @media only screen and (min-width: 320px) {
    .goods {
      div {
        padding: 0 10px;
      }
    }
  }
  @media only screen and (min-width: 400px) {
    .goods {
      div {
        padding: 0 20px;
      }
    }
  }
  .item-filter {
    display: flex;
    justify-content: space-between;
    white-space: nowrap; // flex-wrap: wrap;
    font-size: 12px;
    background: #fff;
    height: 40px;
    line-height: 40px;
    padding: 0 12px;
    margin: 0 8px 12px;
    border-radius: 4px;
    box-shadow: 3px 3px 10px 0px rgba(158, 158, 158, 0.4);
    overflow-x: scroll;
    overflow-y: hidden;
    &::-webkit-scrollbar {
      display: none;
    }
    ul {
      display: flex;
      align-items: center;
      li {
        cursor: pointer;
      }
    }
    .status {
      color: $grey;
      li {
        transition: all .3s;
      }
      li:not(:last-child) {
        margin-right: 12px;
      }
      .active {
        color: $green;
        font-size: 14px;
        border-bottom: 2px solid $green;
      }
    }
  }
  .goods {
    display: flex;
    padding: 0 20px;
    height: 25px;
    position: relative;
    bottom: -1px;
    div {
      margin-right: 5px;
      background: #f7f7f7;
      font-size: 12px;
      box-shadow: 1px 0px 12px 0px rgba(158, 158, 158, 0.3);
      border-radius: 3px;
      height: 25px;
      line-height: 25px;
      color: $grey;
      white-space: nowrap;
      transition: all .5s;
    }
    .active {
      height: 28px;
      line-height: 28px;
      font-size: 14px;
      background: $tmdark;
      color: #fff;
    }
  }
  .filter {
    display: flex;
    justify-content: space-between;
    white-space: nowrap; // flex-wrap: wrap;
    font-size: 14px;
    background: #fff;
    height: 40px;
    line-height: 40px;
    padding: 0 12px; // border-radius: 4px;
    // box-shadow: 3px 3px 10px 0px rgba(158, 158, 158, 0.4);
    border-bottom: 1px solid #dfdfdf;
    ul {
      display: flex;
      align-items: center;
      li {
        cursor: pointer;
      }
    }
    .status {
      color: $grey;
      li {
        transition: all .3s;
      }
      li:not(:last-child) {
        margin-right: 14px;
      }
      .active {
        color: $green;
        font-size: 14px;
        border-bottom: 2px solid $green;
      }
    }
  }
  .item-swiper {
    .button {
      margin-top: 10px;
    }
    .swiper-slide {
      padding: 5px 0;
    }
  }
  .sell-button {
    border: 1px solid #e64340;
    color: #e64340;
  }
  .dash {
    width: 100%;
    border-top: 1px dashed #ccc;
    padding: 5px;
  }
</style>


<style lang="scss">
  .item-table {
    color: #999;
    margin-bottom: 5px;
    font-size: 10px;
    @media only screen and (min-width: 375px) {
      font-size: 10px;
    }
    @media only screen and (min-width: 414px) {
      font-size: 12px;
    }
    @media only screen and (min-width: 768px) {
      font-size: 16px;
    }
    .name {
      max-width: 60px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    td:before {
      display: none;
    }
    th:before {
      display: none;
    }
    &.vux-table:after {
      display: none;
    }
    &.vux-table {
      line-height: 30px;
    }
    button {
      // width: 50px;
      height: 25px;
      line-height: 25px;
      position: relative;
      top: 2px;
    }
  }
  .item-swiper {
    .weui-cell {
      padding: 10px 0;
      &:before {
        left: 0;
      }
    }
  }
</style>
